
import { Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Directive({
    selector: '[appDebounceClick]'
})
/**
 * 防抖指令 
 * 属性：debounceTime：去抖动时间（单位毫秒），单击事件：debounceClick
 * 用法： <button (debounceClick)="savePic(false,'savepic')" appDebounceClick [debounceTime]="3000" >
 *
 */
export class DebounceClickDirective implements OnInit, OnDestroy {
    constructor() {
    }
    @Input() public debounceTime = 300;
    @Output() public debounceClick = new EventEmitter();
    private clicks = new Subject<any>();
    private subscription: Subscription;

    public ngOnInit(): void {
        this.subscription = this.clicks
            .pipe(debounceTime(this.debounceTime))
            .subscribe(e => this.debounceClick.emit(e));
    }
    public ngOnDestroy(): void {
        this.subscription.unsubscribe();
    }

    @HostListener('click', ['$event'])
    public clickEvent(event: MouseEvent): void {
        if (event.currentTarget && event.currentTarget['time'] !== undefined) {
            let orginalTime = event.currentTarget['time'];
            let currentTime = new Date().getTime();
            if (currentTime - orginalTime < 300) {
                return;
            } else {
                event.currentTarget['time'] = currentTime;
            }
        } else {
            event.currentTarget['time'] = new Date().getTime();
        }
        event.preventDefault();
        event.stopPropagation();
        this.clicks.next(event);

    }
}
